package com.lhfeiyu.action.front.user;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.po.base.BaseAccountLog;
import com.lhfeiyu.po.base.BaseOrderInfo;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.po.base.BaseUserFund;
import com.lhfeiyu.po.base.BaseWithdraw;
import com.lhfeiyu.service.AntiqueCityService;
import com.lhfeiyu.service.AuthCheckService;
import com.lhfeiyu.service.base.BaseAccountLogService;
import com.lhfeiyu.service.base.BaseOrderInfoService;
import com.lhfeiyu.service.base.BaseProvinceCityAreaService;
import com.lhfeiyu.service.base.BaseUserFundService;
import com.lhfeiyu.service.base.BaseUserService;
import com.lhfeiyu.service.base.BaseWithdrawService;
import com.lhfeiyu.tools.BankCard_Verify;
import com.lhfeiyu.tools.IDCard_BankName;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.Result;
import com.lhfeiyu.util.base.Md5Util;

@Controller
public class UserPropertyManageaction {
	@Autowired
	private BaseUserService userService;
	@Autowired
	private BaseAccountLogService accountLogService;
	@Autowired
	private BaseProvinceCityAreaService provinceCityAreaService;
	@Autowired
	private AntiqueCityService antiqueCityService;
	@Autowired
	private BaseUserFundService userFundService;
	@Autowired
	private AuthCheckService authCheckService;
	@Autowired
	private BaseWithdrawService withdrawService;
	@Autowired
	private BaseOrderInfoService orderInfoService;
	
	private static Logger logger = Logger.getLogger("R");
	//页面 财务管理主页
	@RequestMapping(value="/propertyManage")
	public ModelAndView propertyManage(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.propertyManage;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/index";
				new ModelAndView(jumpUrl, modelMap);
			}else{
				String jumpUrl = "/user/"+sessionUser.getId();
				new ModelAndView(jumpUrl, modelMap);
			}
			BaseUserFund user = userFundService.selectUserFundByUserId(sessionUser.getId());
			modelMap.put("user", user);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/index", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	//页面 账单管理 账单明细
	@RequestMapping(value="/billDetail")
	public ModelAndView billDetail(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.billDetail;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/index";
				new ModelAndView(jumpUrl, modelMap);
			}else{
				String jumpUrl = "/user/"+sessionUser.getId();
				new ModelAndView(jumpUrl, modelMap);
			}
			BaseUserFund userFUN = userFundService.selectUserFundByUserId(sessionUser.getId());
			modelMap.put("userFUN", userFUN);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/index", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	//页面 充值
	@RequestMapping(value="/recharge")
	public ModelAndView recharge(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.recharge;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/index";
				new ModelAndView(jumpUrl, modelMap);
			}else{
				String jumpUrl = "/user/"+sessionUser.getId();
				new ModelAndView(jumpUrl, modelMap);
			}
			BaseUserFund userFUN = userFundService.selectUserFundByUserId(sessionUser.getId());
			modelMap.put("userFUN", userFUN);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/index", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	//页面 支付方式
	@RequestMapping(value="/remainderRecharge")
	public ModelAndView remainderRecharge(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.remainderRecharge;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/index";
				new ModelAndView(jumpUrl, modelMap);
			}else{
				String jumpUrl = "/user/"+sessionUser.getId();
				new ModelAndView(jumpUrl, modelMap);
			}
			BaseUserFund userFUN = userFundService.selectUserFundByUserId(sessionUser.getId());
			modelMap.put("userFUN", userFUN);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/index", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	//页面 提现
	@RequestMapping(value="/withdrawDeposit")
	public ModelAndView withdrawDeposit(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.withdrawDeposit;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/index";
				new ModelAndView(jumpUrl, modelMap);
			}else{
				String jumpUrl = "/user/"+sessionUser.getId();
				new ModelAndView(jumpUrl, modelMap);
			}
			BaseUser user = userService.selectByPrimaryKey(sessionUser.getId());
			if(null != user.getIsRealAuth()||null != user.getIsEnterpriseAuth()){
				BaseUserFund userFUN = userFundService.selectUserFundByUserId(sessionUser.getId());
				if(null != userFUN.getBankCard1()){
					String bankCard1 = userFUN.getBankCard1();
					modelMap.put("bankCard1", bankCard1.subSequence(bankCard1.length()-4, bankCard1.length()));
				}
				if(null != userFUN.getBankCard2()){
					String bankCard2 = userFUN.getBankCard2();
					modelMap.put("bankCard2", bankCard2.subSequence(bankCard2.length()-4, bankCard2.length()));
				}
				if(null != userFUN.getBankCard3()){
					String bankCard3 = userFUN.getBankCard3();
					modelMap.put("bankCard3", bankCard3.subSequence(bankCard3.length()-4, bankCard3.length()));
				}
				if(null != userFUN.getBankCard4()){
					String bankCard4 = userFUN.getBankCard1();
					modelMap.put("bankCard4", bankCard4.subSequence(bankCard4.length()-4, bankCard4.length()));
				}
				if(null != userFUN.getBankCard5()){
					String bankCard5 = userFUN.getBankCard5();
					modelMap.put("bankCard5", bankCard5.subSequence(bankCard5.length()-4, bankCard5.length()));
				}
				modelMap.put("userFUN", userFUN);		
			}else{
				modelMap.put("isRealAuth", "notRealAuth");
			}
			
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/index", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
/**
 * 申请提现
 * */
	
	@ResponseBody
	@RequestMapping(value = "/addWithdrawApply", method = RequestMethod.POST)
	public JSONObject addWithdrawApply(HttpServletRequest request,ModelMap modelMap,
			@ModelAttribute BaseWithdraw withdraw) {
		JSONObject json = new JSONObject();
		try {
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());// 验证session中的user，存在即返回
			if (null == sessionUser) {
				return Result.userSessionInvalid(json);// 返回session过期的json提示
			}
			Integer userId = sessionUser.getId();
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			BaseOrderInfo orderInfo = orderInfoService.selectByCondition(map);
			if(orderInfo.getOrderDoneStausCode().equals("order_done_status_no")){
				return Result.failure(json, "您当前还有未完成的订单，不能提现保证金", "");
			}
			
			BaseUser user = userService.selectByPrimaryKey(userId);
			Date date = new Date();
			withdraw.setApplyDate(date);
			withdraw.setUserId(userId);
			withdraw.setDealStatus(2);
			withdrawService.insert(withdraw);
			/*添加提现log*/
			BaseAccountLog accountLog = new BaseAccountLog();
			accountLog.setUserId(userId);
			accountLog.setUsername(user.getUsername());
			accountLog.setEmail(user.getEmail());
			accountLog.setPhone(user.getPhone());
			accountLog.setMoney(withdraw.getApplyMoney());
			accountLog.setInOrOut(2);
			accountLog.setPayTime(date);
			accountLog.setAttrStr("提现");
			if(withdraw.getTypeId() == 1){
				accountLog.setPayName("余额");
			}else if(withdraw.getTypeId() == 2){
				accountLog.setPayName("保证金");
			}
			accountLogService.insert(accountLog);
			/*更新用户可用、冻结金额*/
			BaseUserFund userFund = userFundService.selectUserFundByUserId(user.getId());
			BigDecimal nowFrozenMoney = (userFund.getFrozenMoney()).add(withdraw.getApplyMoney());
			if(withdraw.getTypeId() == 1){
				BigDecimal nowMoney = (userFund.getAvaliableMoney()).subtract(withdraw.getApplyMoney());
				userFund.setAvaliableMoney(nowMoney);
			}else if(withdraw.getTypeId() == 2){
				BigDecimal nowMoney = (userFund.getOtherFund()).subtract(withdraw.getApplyMoney());
				userFund.setOtherFund(nowMoney);
			}
			userFund.setFrozenMoney(nowFrozenMoney);
			userFundService.updateMoneyById(userFund);
			
			json.put("msg", "申请提现成功!！");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_设置支付密码出现异常_", json);
		}
		return Result.success(json,"申请提现成功!！");
	}
	
	//获取账单列表
	@ResponseBody
	@RequestMapping(value = "/getBillDetailList", method = RequestMethod.POST)
	public JSONObject getBillDetailList(HttpServletRequest request, ModelMap modelMap
			,@RequestParam(required=false) String r) {
		JSONObject json = new JSONObject();
		try {
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			Map<String, Object> map = ActionUtil.getAllParam(request);
			if(null == sessionUser){	
				String jumpUrl = "/index";
				new ModelAndView(jumpUrl, modelMap);
			}
			map.put("userId", sessionUser.getId());
			List<BaseAccountLog> accountLog = accountLogService.selectListByCondition(map);
			Integer total = accountLogService.selectCountByCondition(map);
			Result.gridData(accountLog, total, json);
//			json.put("accountLog", accountLog);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/getBillDetailList", json);
		}
		return Result.success(json);
	}
	
	
	//绑定银行卡  页面 
	@RequestMapping(value="/bankCardManager")
	public ModelAndView bankCardManager(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.bankCardManager;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/index";
				new ModelAndView(jumpUrl, modelMap);
			}else{
				String jumpUrl = "/user/"+sessionUser.getId();
				new ModelAndView(jumpUrl, modelMap);
			}
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("userId", sessionUser.getId());
			BaseUserFund userFund = userFundService.selectByCondition(map);
			BaseUser user = userService.selectByPrimaryKey(sessionUser.getId());
			if(null == user.getIsRealAuth()){
				modelMap.put("notRealName", "notRealName");
			}
			modelMap.put("userFund", userFund);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/index", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	//添加银行卡  页面 
	@RequestMapping(value="/addCardManager")
	public ModelAndView addCardManager(ModelMap modelMap, HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.addBankCard;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/index";
				new ModelAndView(jumpUrl, modelMap);
			}else{
				String jumpUrl = "/user/"+sessionUser.getId();
				new ModelAndView(jumpUrl, modelMap);
			}
			BaseUser user = userService.selectByPrimaryKey(sessionUser.getId());
			modelMap.put("realName", user.getRealName());
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/index", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@ResponseBody
	@RequestMapping(value = "/checkBankCard", method = RequestMethod.POST)
	public JSONObject checkBankCard(HttpServletRequest request, ModelMap modelMap
			,@RequestParam(required=false) String r) {
		JSONObject json = new JSONObject();
		try {
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			Map<String, Object> map = ActionUtil.getAllParam(request);
			if(null == sessionUser){	
				String jumpUrl = "/index";
				new ModelAndView(jumpUrl, modelMap);
			}
			String bankCardName = (String) map.get("bankCardName");
			String bankCardNum = (String) map.get("bankCardNum");
	
			BaseUserFund userFund = userFundService.selectUserFundByUserId(sessionUser.getId());
			if(bankCardNum.equals(userFund.getBankCard1())){return Result.success(json,"银行卡已存在");}
			if(bankCardNum.equals(userFund.getBankCard2())){return Result.success(json,"银行卡已存在");}
			if(bankCardNum.equals(userFund.getBankCard3())){return Result.success(json,"银行卡已存在");}
			if(bankCardNum.equals(userFund.getBankCard4())){return Result.success(json,"银行卡已存在");}
			if(bankCardNum.equals(userFund.getBankCard5())){return Result.success(json,"银行卡已存在");}
	
			//System.out.println(bankCardName+"bbbb"+bankCardNum);
			BankCard_Verify bank= new BankCard_Verify();
			JSONObject result = bank.idcard_verify(bankCardName,bankCardNum);
			if(null != result){
				int status=Integer.parseInt(result.getString("status"));
				int code=Integer.parseInt(result.getJSONObject("data").getString("code"));
				String message=result.getJSONObject("data").getString("message");
				//System.out.println("code"+code+"aaa"+(code==1102)+((code==1000)));
				if(code==1000){
					//TODO 返回银行卡总行信息
					IDCard_BankName bankName = new IDCard_BankName();
					JSONObject bankNameResult = bankName.idcard_verify(bankCardNum);
					String bankNames=bankNameResult.getJSONObject("status").getString("bankname");
					//System.out.println(bankNameResult + "总行:" +bankNames);

					saveingBankCard(bankCardName,bankCardNum,bankNames,request);
					Result.success(json, "银行卡添加成功");
				}else{	
					Result.success(json, "银行卡验证失败");
				}
			}else{
				Result.success(json, "银行卡验证失败");
			}
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName() + "/getBillDetailList", json);
		}
//		saveingBankCard("1","2","3",request);
		return Result.success(json);
	}
//	public static void main(String[] args) {
////		saveingBankCard("1","2","3");
//	}
	private void saveingBankCard(String bankCardName,String bankCardNum,String bankNames,HttpServletRequest request){
		BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
		if(null == sessionUser){	
			String jumpUrl = "/index";
		}
		BaseUserFund userFund = userFundService.selectByPrimaryKey(sessionUser.getId());
		//System.out.println(userFund);
		if(null == userFund.getBankCard1()){
			userFund.setBankCard1(bankCardNum);
			userFund.setBankUsername1(bankCardName);
			userFund.setBankName1(bankNames);
		}
		else if(null == userFund.getBankCard2()&&null != userFund.getBankCard1()){
			userFund.setBankCard2(bankCardNum);
			userFund.setBankUsername2(bankCardName);
			userFund.setBankName2(bankNames);
		}
		else if(null == userFund.getBankCard3()&&null != userFund.getBankCard2()&&null != userFund.getBankCard1()){
			userFund.setBankCard3(bankCardNum);
			userFund.setBankUsername3(bankCardName);
			userFund.setBankName3(bankNames);
		}
		else if(null == userFund.getBankCard4()&&null != userFund.getBankCard3()&&null != userFund.getBankCard2()&&null != userFund.getBankCard1()){
			userFund.setBankCard4(bankCardNum);
			userFund.setBadkUsername4(bankCardName);
			userFund.setBankName4(bankNames);
		}
		else if(null == userFund.getBankCard5()&&null != userFund.getBankCard4()&&null != userFund.getBankCard3()&&null != userFund.getBankCard2()&&null != userFund.getBankCard1()){
			userFund.setBankCard5(bankCardNum);
			userFund.setBankUsername5(bankCardName);
			userFund.setBankName5(bankNames);
		}
		userFundService.updateByPrimaryKey(userFund);
		
	} 
	
	
	//添加银行卡  页面 
		@RequestMapping(value="/bankCardMsg")
		public ModelAndView bankCardMsg(ModelMap modelMap, HttpServletRequest request
				,@RequestParam(required=false) String r) {
			String path = Page.bankCardMsg;
			try{
				JSONObject json = new JSONObject();
				modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
				BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
				if(null == sessionUser){
					String jumpUrl = "/index";
					new ModelAndView(jumpUrl, modelMap);
				}else{
					String jumpUrl = "/user/"+sessionUser.getId();
					new ModelAndView(jumpUrl, modelMap);
				}
			}catch(Exception e){
				path = Page.error;
				Result.catchError(e, logger, this.getClass().getName()+"/index", modelMap);
			}
			return new ModelAndView(path, modelMap);
		}
	
		/*@ResponseBody
		@RequestMapping(value = "/saveBankmsg", method = RequestMethod.POST)
		public JSONObject saveBankmsg(HttpServletRequest request, ModelMap modelMap
				,@RequestParam(required=false) String r) {
			JSONObject json = new JSONObject();
			try {
				modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
				BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
				Map<String, Object> map = ActionUtil.getAllParam(request);
				if(null == sessionUser){	
					String jumpUrl = "/index";
					new ModelAndView(jumpUrl, modelMap);
				}
				String bankName = (String) map.get("bankName");
				String bankPhone = (String) map.get("phone");
				BaseUserFund userFund = userFundService.selectByPrimaryKey(sessionUser.getId());
				if(null == userFund.getBankName1()){
					userFund.setBankName1(bankName);
				}
				else if(null == userFund.getBankName2()&&null != userFund.getBankName1()){
					userFund.setBankName2(bankName);
				}
				else if(null == userFund.getBankName3()&&null != userFund.getBankName2()&&null != userFund.getBankName1()){
					userFund.setBankName3(bankName);
				}
				else if(null == userFund.getBankName4()&&null != userFund.getBankName3()&&null != userFund.getBankName2()&&null != userFund.getBankName1()){
					userFund.setBankName4(bankName);
				}
				else if(null == userFund.getBankName5()&&null != userFund.getBankName4()&&null != userFund.getBankName3()&&null != userFund.getBankName2()&&null != userFund.getBankName1()){
					userFund.setBankName5(bankName);
				}
				userFundService.updateByPrimaryKey(userFund);
				Result.success(json,"添加成功");
			} catch (Exception e) {
				Result.catchError(e, logger, this.getClass().getName() + "/getBillDetailList", json);
			}
			return Result.success(json);
		}*/
		
		//缴纳消保金  页面 
		@RequestMapping(value="/fireInsurance")
		public ModelAndView fireInsurance(ModelMap modelMap, HttpServletRequest request
				,@RequestParam(required=false) String r) {
			String path = Page.fireInsurance;
			try{
				JSONObject json = new JSONObject();
				modelMap = authCheckService.checkWxLogin(request, modelMap, json, false, r);
				BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
				if(null == sessionUser){
					String jumpUrl = "/index";
					new ModelAndView(jumpUrl, modelMap);
				}else{
					String jumpUrl = "/user/"+sessionUser.getId();
					new ModelAndView(jumpUrl, modelMap);
				}
				Map<String, Object> map = new HashMap<String,Object>();
				map.put("userId", sessionUser.getId());
				BaseUserFund userFund = userFundService.selectByCondition(map);
				modelMap.put("userFund", userFund);
			}catch(Exception e){
				path = Page.error;
				Result.catchError(e, logger, this.getClass().getName()+"/index", modelMap);
			}
			return new ModelAndView(path, modelMap);
		}
	
}